package com.example.blog.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.blog.entity.Blog;
import com.example.blog.lang.Result;
import com.example.blog.mapper.BlogMapper;
import com.example.blog.service.BlogService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author anonymous
 * @since 2021-12-15
 */
@CrossOrigin
@RestController
public class BlogController {

    @Autowired
    private BlogMapper blogMapper;
    @Autowired
    private BlogService blogService;

    @GetMapping("/blogs")
    public Result<IPage> blogs(@RequestParam(defaultValue = "5") Integer pageSize,
                               @RequestParam(defaultValue = "1") Integer pageNo) {
        Page<Blog> page = new Page<>(pageNo, pageSize);
        IPage<Blog> blogIPage = blogMapper.selectPage(page, null);
        Result<IPage> result = new Result<>();
        result.succ("操作成功", blogIPage);
        return result;

    }

    @GetMapping("/blog/{id}")
    public Result<Blog> detail(@PathVariable Long id) {
        Blog blog = blogMapper.selectById(id);
        Result<Blog> result = new Result<>();
        result.succ("操作成功", blog);
        return result;
    }

    @PostMapping("/blog/edit")
    public Result<Blog> edit(@RequestBody Blog blog) {
        Blog temp = null;
        if (blog.getId() != null) {
            temp = blogMapper.selectById(blog.getId());
        }else {
            temp=new Blog();
            Date date = new Date();
            temp.setCreated(date);
            temp.setStatus(0);
        }

        BeanUtils.copyProperties(temp,blog,"userId","title","description","content");

        blogService.saveOrUpdate(blog);
        Result<Blog> result = new Result<>();
        result.succ("操作成功", null);
        return result;
    }


}
